﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using CMS.Common.Helpers;
using CMS.Common.Mvc;
using CMS.Data;
using CMS.Service.Common;
using CMS.Service.Repository;
using CMSApplication.Areas.Administration.Models;
using System.Web;

namespace CMSApplication.Areas.Administration.Controllers
{
    public class CustomerController : UTController
    {
        private CustomerRepository _customer_srv = new CustomerRepository();
        private CustomerTypeRepository _customer_type_srv = new CustomerTypeRepository();
        private UserRepositry _user_srv = new UserRepositry();
        private FileUploadRepository file_srv = new FileUploadRepository();

        public ActionResult Index()
        {
            CustomerSearchModel model = new CustomerSearchModel();
            model.GetDataForSL();
            return View(model);
        }

        [Authorize(Roles = "Administrator,Manager")]
        public ActionResult List(int? page)
        {
            List<CustomerModel> model = new List<CustomerModel>();
            var c = _customer_srv.List();
            var t = _customer_type_srv.List();
            foreach (var item in c)
            {
                CustomerModel ml = new CustomerModel();
                CustomerModel.Mapfrom(item, ref ml);
                var type = t.Where(x => x.Id == ml.Type).FirstOrDefault();
                ml.TypeName = type != null ? type.Name : "";
                model.Add(ml);
            }

            return PartialView("_List", model);
        }

        [Authorize(Roles = "Administrator,Manager")]
        public ActionResult Details(int id)
        {
            CustomerModel model = new CustomerModel();
            var order = _customer_srv.GetById(id);
            CustomerModel.Mapfrom(order, ref model);

            return View(model);
        }

        [Authorize(Roles = "Administrator,Manager")]
        [HttpPost]
        public ActionResult Search(CustomerSearchModel model)
        {
            if (model.CreatedOnFrom > DateTime.MinValue)
            {
                model.CreatedOnFrom = new DateTime(model.CreatedOnFrom.Year, model.CreatedOnFrom.Month, model.CreatedOnFrom.Day);
            }
            if (model.CreatedOnTo > DateTime.MinValue)
            {
                model.CreatedOnTo = new DateTime(model.CreatedOnTo.Year, model.CreatedOnTo.Month, model.CreatedOnTo.Day).AddDays(1);
            }

            List<CustomerModel> m = new List<CustomerModel>();
            var c = _customer_srv.Search(model.Keys, model.Type, 0, model.CreatedOnFrom, model.CreatedOnTo);
            var t = _customer_type_srv.List();
            foreach (var item in c)
            {
                CustomerModel ml = new CustomerModel();
                CustomerModel.Mapfrom(item, ref ml);
                var type = t.Where(x => x.Id == ml.Type).FirstOrDefault();
                ml.TypeName = type != null ? type.Name : "";
                m.Add(ml);
            }

            return PartialView("_List", m);
        }

        [Authorize(Roles = "Administrator,Manager")]
        public ActionResult Add()
        {
            CustomerModel model = new CustomerModel();
            model.Id = 0;
            model.Type = 0;
            model.Active = true;
            model.GetDataForSL();
            return View(model);
        }

        [Authorize(Roles = "Administrator,Manager")]
        public ActionResult Edit(int id)
        {
            var entity = _customer_srv.GetById(id);
            CustomerModel model = new CustomerModel();
            CustomerModel.Mapfrom(entity, ref model);
            model.GetDataForSL();
            return View(model);
        }

        [ValidateInput(false)]
        [Authorize(Roles = "Administrator,Manager")]
        public ActionResult AddOrUpdate(CustomerModel model, IEnumerable<HttpPostedFileBase> FileUp)
        {
            if (model.Name == null) model.Name = "";
            if (model.Id == 0) model.CreatedOn = DateTime.Now;
            Customer entity = new Customer();
            CustomerModel.Mapfrom(model, ref entity);
            _customer_srv.CreateOrUpdate(entity);

            return RedirectToAction("Index");
        }

        [Authorize(Roles = "Administrator,Manager")]
        public ActionResult Delete(int Id)
        {
            _customer_srv.Delete(Id);
            return Json(null, JsonRequestBehavior.AllowGet);
        }

        /* TODO: Comments
        [HttpPost]
        public ActionResult UploadFile(OrderModels model, IEnumerable<HttpPostedFileBase> FileUp, string fileNote)
        {
            User _User = new User();
            string Username = HttpContext.User.Identity.Name;
            if (Username != null)
            {
                _User = _user_srv.GetUserByUserName(Username);
            }
            else { return RedirectToAction("LogOn", "Management"); }

            //Uplpoad
            UploadFile(model, FileUp, _User, fileNote);

            //Update order activities
            string action = "Upload " + FileUp.Count() + " files on " + "<a href='" + System.Web.HttpContext.Current.Request.UrlReferrer + "'>" + model.Title + "</a>";
            UpdateOrderActivities(OrderActions.UploadFile, model, action, _User);
            return RedirectToAction("Details", new { id = model.Id });
        }

        [Authorize(Roles = "Administrator,Manager")]
        public ActionResult SendComment(CommentModel cmmModel)
        {
            User _User = new User();
            string Username = HttpContext.User.Identity.Name;
            if (Username != null)
            {
                _User = _user_srv.GetUserByUserName(Username);
            }
            else { return RedirectToAction("LogOn", "Management"); }

            Order orderEntity = _order_srv.GetById(cmmModel.OrderId);
            OrderModels orderModel = new OrderModels();
            OrderModels.ToModel(orderEntity, ref orderModel);

            if (!string.IsNullOrEmpty(cmmModel.Contents))
            {
                var user = _user_srv.GetUserByUserName(User.Identity.Name);
                Comment cmmEntity = new Comment();
                CommentModel.ToEntity(cmmModel, ref cmmEntity);
                cmmEntity.Id = 0;
                cmmEntity.CreatedTime = DateTime.Now;
                cmmEntity.UserId = user.Id;
                cmmEntity.UserName = user.FullName;
                _cmm_srv.CreateOrUpdate(cmmEntity);
                string action = "Comment on " + "<a href='" + System.Web.HttpContext.Current.Request.UrlReferrer + "'>" + orderModel.Title + "</a>";
                UpdateOrderActivities(OrderActions.Comment, orderModel, action, _User);
            }
            return RedirectToAction("Details", new { id = cmmModel.OrderId });
        }

        public ActionResult DeleteFile(int id, int orderID)
        {
            file_srv.Delete(id);
            return RedirectToAction("Details", new { id = orderID });
        }

        public ActionResult DeleteComment(int id, int orderID)
        {
            _cmm_srv.Delete(id);
            return RedirectToAction("Details", new { id = orderID });
        }

        private void UploadFile(OrderModels model, IEnumerable<HttpPostedFileBase> FileUp, User _User, string fileNote)
        {
            if (FileUp != null)
            {
                if (FileUp.Count() > 0)
                {
                    string folder = model.Title;
                    string filenamefinal = string.Empty;
                    folder = EscapeName.Renamefile(folder);

                    foreach (var file in FileUp)
                    {
                        if (file != null)
                        {
                            if (file.ContentLength > 0)
                            {
                                var dir = Server.MapPath("~/Content/File/Remsigns/");
                                var path = "";
                                var db_path = "";
                                bool isImage = false;
                                if (!Directory.Exists(dir))
                                {
                                    Directory.CreateDirectory(dir);
                                }
                                var ext = Path.GetExtension(file.FileName);
                                if (ext == ".gif" || ext == ".jpg" || ext == ".png" || ext == ".jpeg")
                                {
                                    dir = Server.MapPath("~/Content/File/Remsigns/");
                                    if (!Directory.Exists(dir))
                                    {
                                        Directory.CreateDirectory(dir);
                                    }
                                    var filename = Path.GetFileNameWithoutExtension(file.FileName);
                                    //filename = EscapeName.Renamefile(filename);
                                    string tmp = Path.GetRandomFileName().Substring(0, 3);
                                    filenamefinal = EscapeName.Renamefile(folder + "-" + filename + "-" + tmp) + ext;
                                    path = Path.Combine(Server.MapPath("~/Content/File/Remsigns/"), filenamefinal);
                                    db_path = "Content/File/Remsigns/" + filenamefinal;
                                    file.SaveAs(path);
                                    isImage = true;
                                }
                                else if (ext == ".pdf")
                                {
                                    dir = Server.MapPath("~/Content/File/Remsigns/");
                                    if (!Directory.Exists(dir))
                                    {
                                        Directory.CreateDirectory(dir);
                                    }
                                    var filename = Path.GetFileNameWithoutExtension(file.FileName);
                                    //filename = EscapeName.Renamefile(filename);
                                    string tmp = Path.GetRandomFileName().Substring(0, 3);
                                    filenamefinal = EscapeName.Renamefile(folder + "-" + filename + "-" + tmp) + ext;
                                    path = Path.Combine(Server.MapPath("~/Content/File/Remsigns/"), filenamefinal);
                                    db_path = "Content/File/Remsigns/" + filenamefinal;
                                    file.SaveAs(path);
                                }
                                else if (ext == ".doc" || ext == ".docx" || ext == ".xls" || ext == ".xlsx" || ext == ".ppt" || ext == ".pptx")
                                {
                                    dir = Server.MapPath("~/Content/File/Remsigns/");
                                    if (!Directory.Exists(dir))
                                    {
                                        Directory.CreateDirectory(dir);
                                    }
                                    var filename = Path.GetFileNameWithoutExtension(file.FileName);
                                    //filename = EscapeName.Renamefile(filename);
                                    string tmp = Path.GetRandomFileName().Substring(0, 3);
                                    filenamefinal = EscapeName.Renamefile(folder + "-" + filename + "-" + tmp) + ext;
                                    path = Path.Combine(Server.MapPath("~/Content/File/Remsigns/"), filenamefinal);
                                    db_path = "Content/File/Remsigns/" + filenamefinal;
                                    file.SaveAs(path);
                                }
                                else
                                {
                                    dir = Server.MapPath("~/Content/File/Remsigns/");
                                    if (!Directory.Exists(dir))
                                    {
                                        Directory.CreateDirectory(dir);
                                    }
                                    var filename = Path.GetFileNameWithoutExtension(file.FileName);
                                    //filename = EscapeName.Renamefile(filename);
                                    string tmp = Path.GetRandomFileName().Substring(0, 3);
                                    filenamefinal = EscapeName.Renamefile(folder + "-" + filename + "-" + tmp) + ext;
                                    path = Path.Combine(Server.MapPath("~/Content/File/Remsigns/"), filenamefinal);
                                    db_path = "Content/File/Remsigns/" + filenamefinal;
                                    file.SaveAs(path);
                                }

                                FileUpload pt = new FileUpload()
                                {
                                    FileName = filenamefinal,
                                    OrderId = model.Id,
                                    OrderTitle = model.Title,
                                    UploadById = _User.Id,
                                    UploadByName = _User.FullName,
                                    DateUpload = DateTime.Now,
                                    ModifiedById = _User.Id,
                                    ModifiedByName = _User.FullName,
                                    DateModified = DateTime.Now,
                                    CountModified = 0,
                                    FileLink = db_path,
                                    Filekind = ext,
                                    Published = true,
                                    IsImage = isImage,
                                    Note = fileNote
                                };
                                file_srv.CreateOrUpdate(pt);
                            }

                        }
                    }
                }
            }
        }

        private void UpdateOrderActivities(CMS.Service.Enum.OrderActions orderAction, OrderModels model, string action, User _User)
        {
            OrderActivitiesModels orderActModel = new OrderActivitiesModels();
            orderActModel.Id = 0;
            orderActModel.CreatedTime = DateTime.Now;
            orderActModel.Enable = 1;
            orderActModel.OrderId = model.Id;
            orderActModel.OrderUserID = model.OrderById;
            orderActModel.OrderUserName = model.OrderByName;
            orderActModel.UpdateByUserID = _User.Id;
            orderActModel.UpdateByUserName = _User.FullName;
            orderActModel.Actions = action;
            OrderActivity orderActEntity = new OrderActivity();
            OrderActivitiesModels.ToEntity(orderActModel, ref orderActEntity);
            _orderAct_services.CreateOrUpdate(orderActEntity);

            var this_user = _user_srv.GetById(_User.Id);
            var user_role = _user_srv.GetRolesForUser(this_user.UserName);
            var is_admin = user_role.Where(m => m == "Administrator").Count() > 0;

            List<string> mailList = new List<string>();
            if (model.Parties != null)
            {
                List<string> PartiesMail = (List<string>)CMS.Common.Helpers.StringHelpers.ConvertStringToList(model.Parties);
                mailList.AddRange(PartiesMail);
            }
            if (model.StaffID != null)
            {
                List<string> StaffMail = model.StaffID;
                List<string> StaffMail_edited = StaffMail;
                //foreach (var x in StaffMail)
                //    if (is_admin && x == "")
                //    {
                //    }
                //    else
                //    {
                //        StaffMail_edited.Add(x);
                //    }
                //
                if (is_admin)
                    StaffMail_edited = StaffMail.Where(m => m != "").ToList();
                mailList.AddRange(StaffMail_edited);
            }

            var _order_user = _user_srv.GetById(model.OrderById);
            if (_order_user != null)
            {
                mailList.Add(_order_user.Email);
            }

            Order order = new Order();
            OrderModels.ToEntity(model, ref order);

            string host = System.Web.HttpContext.Current.Request.Url.Host;
            SendEmail.SendEmailOrderActivities(order, orderAction, mailList, host);
        }*/
    }
}
